<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="0"
    class="demo-ruleForm"
    status-icon
  >
    <el-form-item prop="username">
      <el-input v-model.trim="ruleForm.username" placeholder="请输入手机号" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model.trim="ruleForm.password"
        type="password"
        placeholder="请输入密码"
      />
    </el-form-item>
    <el-form-item>
      <div id="sc" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onLogin(ruleFormRef)" class="w-[100%]"
        >登录</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { message } from "@/utils/message";
import { useDicitionaryStore } from "@/store/modules/dicitionary";
import { reactive } from "vue";
import { checkMobile } from "../utils/rule";
const router = useRouter();
const dicitionaryStore = useDicitionaryStore();
onMounted(() => {
  // initAwsc();
});
// awsc
// 实例化ic对象
const initAwsc = () => {
  window.AWSC.use("ic", function (state, module) {
    // 初始化
    window.ic = module.init({
      // 应用类型标识。它和使用场景标识（scene字段）一起决定了智能验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的appkey字段值，请务必正确填写。
      appkey: "FFFF0N00000000007E80",
      // 使用场景标识。它和应用类型标识（appkey字段）一起决定了智能验证的业务场景与后端对应使用的策略模型。您可以在阿里云验证码控制台的配置管理页签找到对应的scene值，请务必正确填写。
      scene: "ic_login",
      // 声明智能验证需要渲染的目标元素ID。
      renderTo: "sc",
      // 验证通过时会触发该回调参数。您可以在该回调参数中将会话ID（sessionId）、签名串（sig）、请求唯一标识（token）字段记录下来，随业务请求一同发送至您的服务端调用验签。
      success: function (data) {
        console.log({
          sessionId: data.sessionId,
          sig: data.sig,
          token: data.token
        });

        ruleForm.value.sessionId = data.sessionId;
        ruleForm.value.sig = data.sig;
        ruleForm.value.token = data.token;
      },
      // 验证失败时触发该回调参数
      fail: function (failCode) {
        ElMessage.error("验证失败！请重试！" + failCode);
      },
      // 验证码加载异常时触发该回调参数
      error: function (errorCode) {
        ElMessage.error("验证失败！请重试！" + errorCode);
      }
    });
  });
};
const ruleForm = ref({
  username: "15731973619",
  password: "admin123",
  sessionId: "",
  sig: "",
  token: ""
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<typeof ruleForm>>({
  username: [
    {
      validator: checkMobile,
      trigger: "blur"
    }
  ],
  password: [
    {
      required: true,
      message: "请输入密码！"
    }
  ]
});
const loading = ref(false);
const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername(ruleForm.value)
        .then(() => {
          // 获取后端路由
          initRouter().then(() => {
            router.push(getTopMenu(true).path);
            message("登录成功", { type: "success" });
            // 获取字典
            dicitionaryStore.getDicitionaryList();
          });
        })
        .catch(() => {
          window.ic.reset();
          ruleForm.value = {
            username: "admin",
            password: "admin123",
            sessionId: "",
            sig: "",
            token: ""
          };
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      return fields;
    }
  });
};
</script>
<style lang="scss" scoped>
#sc {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 !important;
}
</style>
